package com.brayan.webapp.controller.general;

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;

import com.brayan.webapp.model.usermgmt.UriAccess;
import com.brayan.webapp.model.usermgmt.Visit;
import com.brayan.webapp.repository.usermgmt.VisitRepository;

/**
 * Use to capture the users selection and avoid penetrating persistence sources.
 * @author Brayan
 *
 * <p/>
 * - Create a new user for the visit, if not logged in.<br/>
 * - Save the IP to the visit<br/>
 * - Add a cookie to identify the user next time together with it's IP<br/>
 * - Save every page access <br/>
 * - 
 * - 
 */
@Named
@SessionScoped
public class VisitController implements Serializable  {
	
	private static final long serialVersionUID = 328741675037993766L;
	
	@Inject
	VisitRepository visitRepoService;
	
	
	public VisitController(){
		visit = new Visit();
	}
	
	Visit visit;
	
	public Visit getVisit() {
		return visit;
	}

	public void setVisit(Visit visit) {
		this.visit = visit;
	}

	public void logResourceAccess(){
		
	};
	
	public void saveUriRequest(HttpServletRequest httpServletRequest){
		
		String uri = httpServletRequest.getRequestURI();
		String ipAddress = httpServletRequest.getRemoteAddr();
		String agent = httpServletRequest.getHeader("user-agent");
		String queryString = httpServletRequest.getQueryString();
		
		
		visit.setIpAddress(ipAddress);
		visit.setClientAgent(agent);
		//visit.setUser();
		//visit.setGeoInfo();
		
		UriAccess uriAccess = new UriAccess();
		if(queryString == null || queryString.isEmpty())
			uriAccess.setUri(uri);
		else
			uriAccess.setUri(uri + "?" + queryString);			
		visit.addToUriAccessList(uriAccess);
		visitRepoService.save(visit);		
	}

}
